const router = require("koa-router")();
const moment = require("moment");
/**
 *
 * @api {get} /app/config/privilege/list 获取特权列表
 *
 */
router.get("/privilege/list", async (ctx, next) => {
  const baas = ctx.baas;
  const privilegeList = await BaaS.Models.privilege.query({}).fetchAll();
  // 查询用户是否已拥有该特权
  const baasPrivilege = await BaaS.Models.baas_privilege
    .query({ where: { baas_id: baas.id } })
    .fetchAll();
  for (const key in privilegeList) {
    for (const k in baasPrivilege) {
      if (privilegeList[key].id == baasPrivilege[k].privilege_id) {
        Object.assign(privilegeList[key], { owner: baasPrivilege[k].baas_id });
      }
    }
  }
  ctx.success(privilegeList);
});
/**
 *
 * @api {get} /app/config/privilege/id/:id 获取特权信息
 *
 */
router.get("/privilege/id/:id", async (ctx, next) => {
  const baas = ctx.baas;
  const { id } = ctx.params;
  const privilegeInfo = await BaaS.Models.privilege
    .query({ where: { id: id } })
    .fetch();
  // 查询用户是否已拥有该特权
  const baasPrivilege = await BaaS.Models.baas_privilege
    .query({ where: { baas_id: baas.id, privilege_id: id } })
    .fetch();
  if (baasPrivilege) {
    Object.assign(privilegeInfo, { owner: baasPrivilege.baas_id });
  }
  ctx.success(privilegeInfo);
});
/**
 *
 * @api {get} /app/config/privilege/buy 购买特权
 *
 */
router.post("/privilege/buy", async (ctx, next) => {
  const user = ctx.user;
  const baas = ctx.baas;
  const post = ctx.post;
  const couponId = post.coupon_id;
  const privilegeInfo = await BaaS.Models.privilege
    .query({ where: { id: post.id } })
    .fetch();
  let privilegePrice = privilegeInfo.price;
  //  判断是否有优惠券，计算剩余金额
  const userCoupon = await BaaS.Models.user_coupon
    .query({ where: { coupon_id: couponId } })
    .fetch({ withRelated: ["coupon"] });
  if (userCoupon) {
    privilegePrice -= userCoupon.coupon.price;
  }
  // 计算剩余金额
  const money = parseFloat(user.money - privilegePrice).toFixed(2);
  if (money < ctx.config("credits")) {
    ctx.error("账户余额不足");
    return;
  }
  if (couponId) {
    // 删除优惠券
    await BaaS.Models.user_coupon
      .forge({
        id: userCoupon.id,
        status: 1
      })
      .save();
  }

  await BaaS.Models.user.forge({ id: user.id, money: money }).save();
  await BaaS.Models.baas_privilege
    .forge({ baas_id: baas.id, privilege_id: post.id })
    .save();
  // 添加消费记录
  await BaaS.Models.cost_log
    .forge({
      user_id: user.id,
      orderid: moment().format("YYMMDDHHmmssS"),
      money: privilegeInfo.price,
      status: 1,
      remark: "购买特权消费"
    })
    .save();
  ctx.success("购买成功");
});

module.exports = router;
